package com.xiaomo.gitee.datamanager.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class ReflectUtils {

    public static void removeFinalModifier(Field field) throws NoSuchFieldException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method getDeclaredFields0 = Class.class.getDeclaredMethod("getDeclaredFields0", boolean.class);
        /*--add-opens java.base/java.lang=ALL-UNNAMED
        --add-opens java.base/java.lang.reflect=ALL-UNNAMED
        --add-opens java.base/sun.reflect.annotation=ALL-UNNAMED*/
        getDeclaredFields0.setAccessible(true);
        Field[] fields = (Field[]) getDeclaredFields0.invoke(Field.class, false);
        getDeclaredFields0.setAccessible(false);
        Field modifiers = null;
        for (Field each : fields) {
            if ("modifiers".equals(each.getName())) {
                modifiers = each;
            }
        }
        assert modifiers != null;
        modifiers.setAccessible(true);
        modifiers.setInt(field,field.getModifiers() & ~Modifier.FINAL);
        modifiers.setAccessible(false);
    }

}
